<?php

class Model_Api_V2_Visa
{
    private static $_typeid = 8;

    public static function get_area_query($pid)
    {
        $pid = $pid ? $pid : 0;
        $sql = 'SELECT id,kindname,pid,pinyin FROM sline_visa_area ';
        $sql .= "WHERE pid={$pid} and isopen=1 and webid=0 ";
        $sql .= 'order by displayorder asc,id desc ';
        $arr = DB::query(1, $sql)->execute()->as_array();
        return $arr;
    }

    public static function search_result($params)
    {
        $kind = $params['area'];
        $sort_type = $params['sort_type'];
        $visatype = $params['visatype'];
        $p = $params['page'];
        $keyword = $params['keyword'];
        $city_id = $params['city_id'];
        $field = 'a.id,a.aid,a.title,a.handleday,a.price,a.litpic,a.cityid,a.bookcount,a.satisfyscore,a.recommendnum,a.visatype,a.needinterview,a.refund_restriction';
        $where = "a.webid=0 AND a.ishidden=0 ";
        if ($kind != 'all') {
            $where .= 'And  b.pinyin=:pinyin ';
        }
        $value_arr[':pinyin'] = $kind;
        if (!empty($city)) {
            $where .= " And a.cityid=:cityid";
            $value_arr[':cityid'] = $city;
        }
        if (!empty($visatype)) {
            $where .= " and a.visatype=:visatype";
            $value_arr[':visatype'] = $visatype;
        }
        if (!empty($keyword)) {
            $where .= "And  a.title like '%{$keyword}%' ";
        }
        if (!empty($city_id)) {
            $where .= "And  a.cityid={$city_id} ";
        }
        //排序
        $orderBy = "";
        if (!empty($sort_type)) {
            if ($sort_type == 1)//价格升序
            {
                $orderBy = "  CONVERT (a.price, SIGNED) ASC,";
            } else if ($sort_type == 2) //价格降序
            {
                $orderBy = "  CONVERT (a.price, SIGNED) DESC,";
            } else if ($sort_type == 3) //销量降序
            {
                $orderBy = "  CONVERT (a.bookcount, SIGNED) DESC,";
            } else if ($sort_type == 4)//推荐
            {
                $orderBy = " a.recommendnum DESC,";
            }
        }

        $offset = ($p - 1) * 10;
        $sql = "SELECT {$field} FROM sline_visa AS a LEFT JOIN sline_visa_area AS b ON (a.areaid = b.id OR a.nationid = b.id) LEFT JOIN `sline_allorderlist` c ON (a.id=c.aid AND c.typeid=8 AND a.webid=c.webid)  ";
        $sql .= "WHERE {$where} ";
        $sql .= "ORDER BY {$orderBy} IFNULL(c.displayorder,9999) ASC,a.id DESC ";
        $sql .= "LIMIT {$offset},10";
        $data = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();

        foreach ($data as &$v) {
            $v['litpic'] = Model_Api_V2_System::uniapp_img($v['litpic'],750,400);
            $v['satisfyscore'] = Model_Comment::get_score($v['id'], self::$_typeid, $v['satisfyscore'], $v['commentnum']);//满意度
            $v['sellnum'] = Model_Member_Order::get_sell_num($v['id'], self::$_typeid) + intval($v['bookcount']);
            $city = Model_Visa::visa_city_by_id($v['cityid']);
            if (is_array($city)) {
                $city = $city['kindname'];
            }
            $v['city'] = $city;
            $v['price'] = Currency_Tool::price($v['price']);
        }
        $out = array(
            'total' => count($data),
            'list' => $data,
            'status' => true
        );
        return $out;
    }

    public static function get_info($id, $userid = '')
    {
        $info = DB::select()->from('visa')->where('id', '=', $id)->execute()->current();

        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::$_typeid);
        $info['satisfyscore'] = Model_Comment::get_score($info['id'], self::$_typeid, $info['satisfyscore'], $info['commentnum']);//满意度
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], self::$_typeid) + intval($info['bookcount']);
        $info['attachment'] = unserialize($info['attachment']);
        if($info['visatype']){
            $visa_type = DB::select('kindname')->from('visa_kind')->where('id', '=', $info['visatype'])->execute()->get('kindname');
        }else{
            $visa_type = '';
        }
        $info['visa_type'] = $visa_type;
        $info['litpic'] = Model_Api_V2_System::reorganized_resource_url($info['litpic']);

        $info['extend_info'] = Model_Visa::visa_extend($info['id']);
        foreach ($info['extend_info'] as &$v){
            $v['content'] = Model_Api_V2_Xcx::filter_content($v['content']);
        }
        $info['cityname'] = DB::select()->from('visa_city')->where('id', '=', $info['cityid'])->execute()->get('kindname');

        foreach ($info['attachment']['path'] as $k => $path) {
            $info['attachment']['path'][$k] = Model_Api_V2_System::reorganized_resource_url($path);
        }

        $materials = Model_Visa_Material::get_list(1);
        foreach ($materials as &$ma) {
            $content = Model_Visa_Material_Content::get_content($info['id'], $ma['pinyin']);
            $ma['content'] = Model_Api_V2_Xcx::filter_content($content);
        }
        $info['materials'] = $materials;
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认支付'
        );
        $info['paytype_name'] = $pay_name[$info['paytype']];
        // 获取产品编号
        $info['serial_number'] = St_Product::product_series($id, self::$_typeid);
        // 更加ID查询可用的优惠券
        if (St_Functions::is_normal_app_install('coupon')) {
            $info['coupon_list'] = Model_Coupon::get_product_coupon_list($id, self::$_typeid);
        }
        //
        $nation = DB::select('pid', 'kindname')->from('visa_area')->where('id', '=', $info['nationid'])->execute()->current();
        $nation_name = DB::select('kindname')->from('visa_area')->where('id', '=', $nation['pid'])->execute()->get('kindname');
        $info['nation'] = $nation;
        $info['nation_name'] = $nation_name;


        //分销赚取的金额
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            if (!empty($userid)) {
                $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid", '=', $userid)->execute()->current();
                $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_' . self::$_typeid, $fxgroupid['fxgroupid']);

                if ($commission_type == 1) {
                    $commission_rate = Model_Fenxiao::get_commission_rate(self::$_typeid, $id, $fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_rate[0] * 100;
                    $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                    $v['commission'] .= '%';
                    $v['profit'] = $info['price'] * $commission_rate[0];
                } else if ($commission_type == 2) {
                    $commission_rate = Model_Fenxiao::get_commission_rate_platform(self::$_typeid, $id, $fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_rate[0] * 100;
                    $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                    $v['commission'] .= '%';
                    $temp_order = array('typeid' => self::$_typeid, 'productautoid' => $id, 'totalprice' => $info['price'], 'dingnum' => 1);
                    $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                    $platform_price = $platform_price == 0 ? $info['price'] : $platform_price;
                    $v['profit'] = $platform_price * $commission_rate[0];
                } else {
                    $commission_cash = Model_Fenxiao::get_commission_cash_line(self::$_typeid, $id, $fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_cash[0]['adult'];
                    $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                    $v['profit'] = $v['commission'];
                }
                $info['profit'] = $v['profit'];
            }
        }
        return $info;
    }

    public static function get_content($params)
    {
        $default = array(
            'typeid' => '',
            'productinfo' => 0,
            'onlyrealfield' => 0,
            'pc' => 0

        );
        $params = array_merge($default, $params);
        extract($params);
        if (empty($typeid))
        {
            return array();
        }
        $tables = array(
            '1' => 'sline_line_content',
            '2' => 'sline_hotel_content',
            '3' => 'sline_car_content',
            '5' => 'sline_spot_content',
            '8' => 'sline_visa_content',
            '13' => 'sline_tuan_content',
        );
        $extend_tables = array(
            '1' => 'sline_line_extend_field',
            '2' => 'sline_hotel_extend_field',
            '3' => 'sline_car_extend_field',
            '5' => 'sline_spot_extend_field',
            '8' => 'sline_visa_extend_field',
            '13' => 'sline_tuan_extend_field',
        );

        $table = $tables[$typeid];
        $extend_tables = $extend_tables[$typeid];
        $where = '';
        if (empty($table))
        {
            //扩展产品
            $isExists = DB::select()->from('model')->where("id={$typeid}")->execute()->current();
            if (empty($isExists))
            {
                return '';
            }
            $table = 'sline_model_content';
            $extend_tables = "sline_{$isExists['addtable']}";
            $where = 'typeid=' . $typeid . ' and ';
        }
        $sql = "SELECT columnname,chinesename,isrealfield FROM {$table} ";
        $sql .= "WHERE $where webid=0 and isopen=1 ";
        $sql .= "ORDER BY displayorder ASC";
        $arr = DB::query(1, $sql)->execute()->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $sql = "SELECT * FROM $extend_tables WHERE productid='$productid'";
        $ar = DB::query(1, $sql)->execute()->as_array();
        $list = array();
        foreach ($arr as $v)
        {
            if ($v['columnname'] == 'tupian')
            {
                continue;
            }
            if ($v['isrealfield'] == 1)
            {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
            }
            //是否只显示真实字段
            else if ($onlyrealfield == 1)
            {
                $content = '';
            }
            else
            {
                $content = $productid;
            }
            //行程附件
            if ($v['columnname'] == 'linedoc')
            {
                if ('array' == strtolower($content))
                {
                    $content = null;
                }
            }
            if (empty($content))
            {
                if ($v['columnname'] == "payment")
                {
                    $payment = DB::select()->from('sysconfig')->where('varname', '=', 'cfg_payment')->and_where('webid','=',$GLOBALS['sys_webid'])->execute()->current();
                    if (!$payment)
                    {
                        continue;
                    }
                    $content=$payment['value'];
                }
                else
                {
                    continue;
                }

            }

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];
            if ($typeid == 1 && $v['columnname'] == 'jieshao' && $productinfo['isstyle'] == 2)
            {
                $lineContent = DB::query(1, "SELECT * FROM sline_line_jieshao where lineid ={$content} and `day`=1 and title!='' and title is not null")->execute()->current();
                if (!$lineContent)
                {
                    continue;
                }
            }
            if ($typeid == 1 && $v['columnname'] == 'jieshao' && $productinfo['isstyle'] == 1)
            {
                $content = $productinfo['jieshao'];
                if (empty($content))
                {
                    continue;
                }
            }
            // $content = Product::replace_strong_to_span($content);
            $a['content'] = $pc == 0 ? Product::strip_style($content) : $content; //针对PC/手机版选择是否去样式.

            $list[] = $a;

        }
        return $list;
    }

}